<template>
  <el-dialog
    v-model="visible"
    title="创建试卷模板"
    width="800px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="模板名称" prop="title">
        <el-input
          v-model="form.title"
          placeholder="请输入模板名称"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="适用学科" prop="subject">
        <el-select
          v-model="form.subject"
          placeholder="请选择学科"
          style="width: 100%"
        >
          <el-option label="语文" value="chinese" />
          <el-option label="数学" value="math" />
          <el-option label="英语" value="english" />
          <el-option label="物理" value="physics" />
          <el-option label="化学" value="chemistry" />
          <el-option label="生物" value="biology" />
          <el-option label="历史" value="history" />
          <el-option label="地理" value="geography" />
          <el-option label="政治" value="politics" />
        </el-select>
      </el-form-item>

      <el-form-item label="适用年级" prop="grade">
        <el-select
          v-model="form.grade"
          placeholder="请选择年级"
          style="width: 100%"
        >
          <el-option label="一年级" value="1" />
          <el-option label="二年级" value="2" />
          <el-option label="三年级" value="3" />
          <el-option label="四年级" value="4" />
          <el-option label="五年级" value="5" />
          <el-option label="六年级" value="6" />
          <el-option label="七年级" value="7" />
          <el-option label="八年级" value="8" />
          <el-option label="九年级" value="9" />
          <el-option label="高一" value="10" />
          <el-option label="高二" value="11" />
          <el-option label="高三" value="12" />
        </el-select>
      </el-form-item>

      <el-form-item label="总分" prop="total_score">
        <el-input-number
          v-model="form.total_score"
          :min="10"
          :max="200"
          :step="10"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="及格分数" prop="passing_score">
        <el-input-number
          v-model="form.passing_score"
          :min="1"
          :max="form.total_score - 1"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="考试时长" prop="duration">
        <el-input-number
          v-model="form.duration"
          :min="30"
          :max="300"
          :step="15"
          style="width: 100%"
        />
        <span style="margin-left: 8px; color: #909399;">分钟</span>
      </el-form-item>

      <el-form-item label="难度等级" prop="difficulty_level">
        <el-radio-group v-model="form.difficulty_level">
          <el-radio value="easy">简单</el-radio>
          <el-radio value="medium">中等</el-radio>
          <el-radio value="hard">困难</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="模板描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="4"
          placeholder="请输入模板描述"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-divider content-position="left">题型结构</el-divider>

      <el-form-item label="选择题">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-input-number
              v-model="form.question_types.choice.count"
              :min="0"
              :max="50"
              placeholder="数量"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="8">
            <el-input-number
              v-model="form.question_types.choice.score"
              :min="1"
              :max="10"
              placeholder="单题分值"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="8">
            <span class="item-total">
              总分: {{ form.question_types.choice.count * form.question_types.choice.score }}
            </span>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="填空题">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-input-number
              v-model="form.question_types.fill_blank.count"
              :min="0"
              :max="30"
              placeholder="数量"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="8">
            <el-input-number
              v-model="form.question_types.fill_blank.score"
              :min="1"
              :max="10"
              placeholder="单题分值"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="8">
            <span class="item-total">
              总分: {{ form.question_types.fill_blank.count * form.question_types.fill_blank.score }}
            </span>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="判断题">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-input-number
              v-model="form.question_types.judgment.count"
              :min="0"
              :max="20"
              placeholder="数量"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="8">
            <el-input-number
              v-model="form.question_types.judgment.score"
              :min="1"
              :max="5"
              placeholder="单题分值"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="8">
            <span class="item-total">
              总分: {{ form.question_types.judgment.count * form.question_types.judgment.score }}
            </span>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="简答题">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-input-number
              v-model="form.question_types.short_answer.count"
              :min="0"
              :max="10"
              placeholder="数量"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="8">
            <el-input-number
              v-model="form.question_types.short_answer.score"
              :min="5"
              :max="20"
              placeholder="单题分值"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="8">
            <span class="item-total">
              总分: {{ form.question_types.short_answer.count * form.question_types.short_answer.score }}
            </span>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="作文题">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-input-number
              v-model="form.question_types.essay.count"
              :min="0"
              :max="3"
              placeholder="数量"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="8">
            <el-input-number
              v-model="form.question_types.essay.score"
              :min="10"
              :max="50"
              placeholder="单题分值"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="8">
            <span class="item-total">
              总分: {{ form.question_types.essay.count * form.question_types.essay.score }}
            </span>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirm" :loading="loading">
        确认创建
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success', data: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref()
const loading = ref(false)

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const form = reactive({
  title: '',
  subject: '',
  grade: '',
  total_score: 100,
  passing_score: 60,
  duration: 120,
  difficulty_level: 'medium',
  description: '',
  question_types: {
    choice: { count: 20, score: 2 },
    fill_blank: { count: 10, score: 2 },
    judgment: { count: 10, score: 1 },
    short_answer: { count: 3, score: 10 },
    essay: { count: 1, score: 30 }
  }
})

const rules = {
  title: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '请选择学科', trigger: 'change' }
  ],
  grade: [
    { required: true, message: '请选择年级', trigger: 'change' }
  ],
  total_score: [
    { required: true, message: '请输入总分', trigger: 'blur' },
    { type: 'number', min: 10, max: 200, message: '总分在 10-200 之间', trigger: 'blur' }
  ],
  passing_score: [
    { required: true, message: '请输入及格分数', trigger: 'blur' },
    { type: 'number', min: 1, message: '及格分数必须大于0', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请输入考试时长', trigger: 'blur' },
    { type: 'number', min: 30, max: 300, message: '时长在 30-300 分钟之间', trigger: 'blur' }
  ],
  difficulty_level: [
    { required: true, message: '请选择难度等级', trigger: 'change' }
  ]
}

// 计算总分
const calculatedTotal = computed(() => {
  const types = form.question_types
  return types.choice.count * types.choice.score +
         types.fill_blank.count * types.fill_blank.score +
         types.judgment.count * types.judgment.score +
         types.short_answer.count * types.short_answer.score +
         types.essay.count * types.essay.score
})

// 监听题型变化，自动更新总分
watch(
  () => form.question_types,
  () => {
    form.total_score = calculatedTotal.value
  },
  { deep: true }
)

// 监听总分变化，自动调整及格分数
watch(
  () => form.total_score,
  (newScore) => {
    if (form.passing_score >= newScore) {
      form.passing_score = Math.floor(newScore * 0.6)
    }
  }
)

const handleClose = () => {
  visible.value = false
  resetForm()
}

const resetForm = () => {
  Object.assign(form, {
    title: '',
    subject: '',
    grade: '',
    total_score: 100,
    passing_score: 60,
    duration: 120,
    difficulty_level: 'medium',
    description: '',
    question_types: {
      choice: { count: 20, score: 2 },
      fill_blank: { count: 10, score: 2 },
      judgment: { count: 10, score: 1 },
      short_answer: { count: 3, score: 10 },
      essay: { count: 1, score: 30 }
    }
  })
  formRef.value?.clearValidate()
}

const handleConfirm = async () => {
  try {
    await formRef.value.validate()

    // 验证总分是否匹配
    if (calculatedTotal.value !== form.total_score) {
      ElMessage.warning(`题型总分(${calculatedTotal.value})与设置总分(${form.total_score})不匹配，已自动调整`)
      form.total_score = calculatedTotal.value
    }

    loading.value = true

    // TODO: 调用API创建模板
    // await examPaperApi.createTemplate(form)

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    ElMessage.success('模板创建成功')
    emit('success', { ...form })
    handleClose()
  } catch (error) {
    console.error('创建模板失败:', error)
    ElMessage.error('创建模板失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.item-total {
  display: inline-flex;
  align-items: center;
  height: 32px;
  color: #409eff;
  font-weight: 500;
}

:deep(.el-divider__text) {
  background-color: #f5f5f5;
}
</style>